package com.ideaction.hotswap;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.lang.instrument.ClassDefinition;
import java.lang.instrument.Instrumentation;

/**
 * 探针执行入口
 * 
 * @author ZGame
 *
 */
public class MyAgent {

	public static void agentmain(String codePath, Instrumentation inst) {
		try {
			File f = new File(codePath);
			int readCount = 0;
			FileInputStream in = null;
			ByteArrayOutputStream buffer = null;
			try {
				in = new FileInputStream(f);
				buffer = new ByteArrayOutputStream();
				while ((readCount = in.read()) != -1) {
					buffer.write(readCount);
				}
				reloadClass(buffer.toByteArray(), inst);
			} finally {
				if (in != null) {
					in.close();
				}
				if (buffer != null) {
					buffer.close();
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private static void reloadClass(byte[] targetClassFile, Instrumentation inst) throws Exception {
		DynamicClassLoader myLoader = new DynamicClassLoader();
		Class<?> targetClazz = myLoader.findClass(targetClassFile);
		ClassDefinition clazzDef = new ClassDefinition(Class.forName(targetClazz.getName()), targetClassFile);
		inst.redefineClasses(clazzDef);
	}
}
